package com.looncin.oj.judge.codesandbox.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.looncin.oj.common.ErrorCode;
import com.looncin.oj.exception.BusinessException;
import com.looncin.oj.judge.codesandbox.CodeSandBox;
import com.looncin.oj.judge.codesandbox.model.ExecuteCodeRequest;
import com.looncin.oj.judge.codesandbox.model.ExecuteCodeResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 远程代码沙箱（实际项目要用）
 */
@Slf4j
@Component
public class RemoteCodeSandBoxImpl implements CodeSandBox {

//    @Value("${codesandbox.remote.url:'http://localhost:8201/api/executecode'}")
    private String url;

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        log.info("进入调用代码沙箱接口,url={}", url);
        url = "http://111.230.204.223:8201/api/executecode";
//        url = "http://38.55.201.56:8301/api/executecode"; //chen的api
        String jsonStr = JSONUtil.toJsonStr(executeCodeRequest);
        String responseBodyStr = HttpUtil.createPost(url)
                .header("auth", "7758521")
                .body(jsonStr)
                .execute()
                .body();
        if (StringUtils.isBlank(responseBodyStr)) {
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR, "executeCode remoteCodeSandBox error, message=" + responseBodyStr);
        }
        return JSONUtil.toBean(responseBodyStr, ExecuteCodeResponse.class);
    }
}
